package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import pojo.Wrapper;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author chenx
 * @date 2021/8/25-22:42
 */
public class Bootstrap {
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() throws Exception {
        // 加载解析相关的配置，web.xml
        Service server = new Service();
        server.loadEngin();
        List<Wrapper> servletList = server.getServletList();
        //定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        //线程池工厂
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        //拒绝策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler);

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("==========MiniCat start on port:" + port);

        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
       /* while (true){
            Socket socket = serverSocket.accept();
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello MiniCat !";
            String responseText =
                    HttpProtocolUtil.getHttpHeader200(data.getBytes().length)+data;
            outputStream.write(responseText.getBytes());
            socket.close();

        }*/

        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
       /* while (true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            response.outputHtml(request.getUrl());
            socket.close();

        }*/
        /**
         * 完成Minicat 3.0版本
         * 需求：请求动态资源
         */
      /* while (true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
           Response response = new Response(socket.getOutputStream());
            if (servletMap.get(request.getUrl())==null){
                //静态资源
                response.outputHtml(request.getUrl());
            }else{
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }
            socket.close();

        }*/

        /**
         * 完成Minicat 4.0版本
         * 需求：多线程（不使用线程池）
         */
       /* while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            requestProcessor.start();
        }*/
        System.out.println("=========>>>线程池");
        /**
         * 完成Minicat 4.0版本
         * 需求：多线程（使用线程池）
         */
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletList);
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    /**
     * 加载解析web.xml，初始化Servlet
     */
//    private void loadServlet(){
//        try {
//            // InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
//            String path = "E:\\webapps\\demo1\\web.xml";
//            InputStream resourceAsStream = new FileInputStream(path);
//            SAXReader saxReader = new SAXReader();
//            Document document = saxReader.read(resourceAsStream);
//            Element rootElement = document.getRootElement();
//
//            List<Element> selectNodes = rootElement.selectNodes("//servlet");
//            for (int i = 0; i < selectNodes.size(); i++) {
//                Element element = selectNodes.get(i);
//                // <servlet-name>lagou</servlet-name>
//                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
//                String servletName = servletnameElement.getStringValue();
//                // <servlet-class>server.LagouServlet</servlet-class>
//                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
//                String servletClass = servletclassElement.getStringValue();
//
//
//                // 根据servlet-name的值找到url-pattern
//                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
//                // /my
//                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
//                WebClassLoader webClassLoader = new WebClassLoader();
//                Class<?> aClass = webClassLoader.findClass("E:\\webapps\\demo1\\", servletClass);
//                servletMap.put(urlPattern, (HttpServlet)aClass.getDeclaredConstructor().newInstance());
//
//            }
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
}
